package main

import (
	"devOpsApi/config/ymlgo"
	syscron "devOpsApi/cron"
	"devOpsApi/libs"
	"devOpsApi/middleware"
	"devOpsApi/route"
	"fmt"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
	"github.com/robfig/cron"
	"github.com/rs/cors"
	"net/http"
)

func init() {
	mysqlConfig := ymlgo.NewMysqlConfig()
	dbConfig := libs.DbConfig{
		Host:         mysqlConfig.MysqlHost,
		Port:         mysqlConfig.MysqlPort,
		Database:     mysqlConfig.MysqlDatabase,
		User:         mysqlConfig.MysqlUser,
		Password:     mysqlConfig.MysqlPwd,
		Charset:      mysqlConfig.MysqlCharset,
		MaxIdleConns: mysqlConfig.MysqlMaxIdleConns,
		MaxOpenConns: mysqlConfig.MysqlOpenConns,
	}
	libs.DB = dbConfig.InitDB()
	if mysqlConfig.MysqlSqlLog == true {
		libs.DB.LogMode(true)
	}
	libs.InitCache()
}

func main() {
	app := iris.New()
	app.Logger().SetLevel("warn")

	//（可选）添加两个内置处理程序
	//可以从任何与http相关的panics中恢复
	//并将请求记录到终端。
	app.Use(recover.New())
	app.Use(logger.New())
	//文件目录
	app.StaticWeb("/uploads", "./uploads") //设置静态文件目录
	//路由
	route.Routes(app)
	//跨域运行设置
	corsOptions := cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{
			http.MethodHead,
			http.MethodGet,
			http.MethodPost,
			http.MethodPut,
			http.MethodPatch,
			http.MethodDelete,
		},
		AllowedHeaders:   []string{"*"},
		AllowCredentials: false,
	}
	corsWrapper := cors.New(corsOptions).ServeHTTP
	app.WrapRouter(corsWrapper)

	//针对OPTIONS请求进行验证
	app.OnAnyErrorCode(func(ctx iris.Context) {
		if ctx.Method() == "OPTIONS" {
			ctx.StatusCode(200)
			_, _ = ctx.WriteString("OPTIONS SUCCESS")
			ctx.Next()
		}
	})

	/*
		Xterm.js websocket
	*/
	XtermWs := middleware.GetXtermWsServer()
	XtermWs.ReceiveMessage()
	app.Get("/xterm", XtermWs.ServerRs.Handler())

	/*
		pipeline websocket
	*/
	PipelineWs := middleware.GetPipelineWsServer()
	PipelineWs.ReceiveMessage()
	app.Get("/pipeline", PipelineWs.ServerRs.Handler())

	config := ymlgo.NewConfigSysBase()

	go func() {
		SysCron()
	}()

	if err := app.Run(iris.Addr(":" + config.ServerPort)); err != nil {
		fmt.Println("服务启动失败,错误代码 %s", err)
		panic("服务启动失败,错误代码" + err.Error())
	}
}

//系统定时日志
func SysCron() {
	c := cron.New()
	//清理Docker容器 每小时执行一次
	go syscron.CleanOvertTimeDocker()
	_ = c.AddFunc("@hourly", func() {
		go syscron.CleanOvertTimeDocker()
	})

	//@every 1m
	//0 * * * * *
	_ = c.AddFunc("0 * * * * *", func() {
		go syscron.RunPipeline()
	})
	c.Start()
	select {}
}
